package com.just.fun.arithmetic;

/**
 * 判断链表中是否有环
 * 判断给定的链表中是否有环。如果有环则返回true，否则返回false。
 * 你能给出空间复杂度O(1)的解法么？
 */
public class LinkTest2 {

    public static void main(String[] args) {
        ListNode listNode=new ListNode(1);
        listNode.next=new ListNode(2);
        ListNode node3=new ListNode(3);
        listNode.next=node3;
        node3.next=new ListNode(4);
        node3.next.next=new ListNode(5);
        ListNode cycle=new ListNode(6);
        node3.next.next.next=cycle;
        cycle.next=node3;
        System.out.println(hasCycle(listNode));

        System.out.println("结环点："+findLoop(listNode).val);
    }

    /**
     * 快慢指针算法
     * @param head
     * @return
     */
    public static boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    /**
     * 拓展：寻找结环点
     * @param head
     * @return
     */
    public static ListNode findLoop(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
        boolean isLoop=false;
        //先找到碰撞点
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                isLoop=true;
                break;
            }
        }
        //指针1从头节点到碰撞点
        //指针2从碰撞点一直往前走
        if(isLoop){
            slow=head;
            while (fast!=null){
                slow=slow.next;
                fast=fast.next;
                if(slow==fast){
                    return slow;
                }
            }
        }
        return null;
    }

    /**
     * 定义一个链表类
     */
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }
}
